#!/bin/bash
#
# Pulley routines and globals for managing commands
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 18 November 2013
#
#   Copyright 2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.


## command_summary <command name>
##
## Echoes the command summary for <command name> if <command name> is
## defined. Otherwise displays an error message to standard error. Returns
## 0 on success, non-zero otherwise.
##
function command_summary() {
	local status=0
	
	if lazy_load p_cmd_$1_summary "commands" "$1.command"; then
		p_cmd_$1_summary
		status=$?
	else
		echo "Unknown command: $1"
		status=2
	fi
	
	return ${status}
}


## command_help <command name>
##
## Echoes command help information for <command name> if <command name> is
## valid. Otherwise, returns non-zero status and writes an error message to
## standard error. Returns 0 on success.
##
function command_help() {
	local status=0
	
	if lazy_load p_cmd_$1_help "commands" "$1.command"; then
		p_cmd_$1_help
		status=$?
	else
		echo "Unknown command: $1"
		status=2
	fi
	
	return ${status}
}


## run_command <command name> [args ...]
##
## Runs the command specified by <command name>, along with optional
## arguments [args ...]. If the first argument to the command is --help,
## displays command help on standard output instead of executing the command.
##
## If the requested command is invalid, displays an error message on standard
## error and returns status code 2. Otherwise, returns the exit status of
## the command.
##
function run_command() {
	local status=0
	local cmd=$1
	shift
	
	# Convert any dashes in the command to underscores
	cmd=$(echo "${cmd}" | sed s/-/_/g)
	
	if lazy_load p_cmd_${cmd} "commands" "${cmd}.command"; then
		# Peek to see if the user really wants --help
		if [[ "$1" == "--help" ]]; then
			command_help ${cmd}
		else
			p_cmd_${cmd} "$@"
			status=$?
		fi
	else
		echo "Unknown command: ${cmd}"
		status=2
	fi
	return ${status}
}


## load_all_commands
##
## Loads all the .command files from the commands subdirectory of the
## Pulley library directory. Returns 0 on success, non-zero if an error is
## detected.
##
function load_all_commands() {
	local status=0
	
	for module in $(ls "${P_LIBDIR}/commands"/*.command); do
		. "${module}"
		status=$(merge_status ${status} $?)
	done
	
	return ${status}
}
